package ChatSystem;
import java.io.ByteArrayOutputStream;
import java.io.ObjectOutputStream;
import java.net.*;

import chatsystemTDa2.*;

/**
 * Instances of this class could be used to send ChatSystem messages over a UDP connection.
 */
public class UDPSender {
	
	/**
	 * Initializes the sender.
	 */
	public UDPSender() {

	}
	
	/**
	 * Sends a ChatSystem messages over a UDP connection
	 * @param message The message to send
	 * @param address The address where the recipient is located
	 * @param port The port used to reach the recipient
	 */
	public void sendMessage(Message message, InetAddress address, int port) {
		try {
			ByteArrayOutputStream bytes = new ByteArrayOutputStream();
		    ObjectOutputStream objectStream = new ObjectOutputStream(bytes);
			objectStream.writeObject(message);
			objectStream.flush();
			byte[] buf = bytes.toByteArray();
			
			DatagramSocket clientSocket = new DatagramSocket();
			DatagramPacket packet = new DatagramPacket(buf, buf.length, address, port);
			
			clientSocket.send(packet);
			clientSocket.close();
		} catch(Exception e) {}
	}
}
